package com.tjtt.tdm.system.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.tjtt.common.utils.StringUtil;
import com.tjtt.tdm.base.BaseAction;
import com.tjtt.tdm.base.PageResult;
import com.tjtt.tdm.exception.ServiceException;
import com.tjtt.tdm.system.bean.SysCerify;
import com.tjtt.tdm.system.service.CerifyService;
import com.tjtt.tdm.system.service.LogService;

public class CerifyAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	private static final Log log = LogFactory.getLog(CerifyAction.class);
	private CerifyService cerifyService;
	private LogService logService;
	private SysCerify sysCerify;
	
	
	private List upload; 
	private List uploadContentType; 
	private List uploadFileName; 
	
	/**
	 * 保存用户里证书的信息
	 * @return
	 * @throws IOException
	 * @throws ServiceException
	 */
	public String saveCerifyExec() throws Exception {
		setContentType();
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = response.getWriter(); 
		String contentType = this.getRequest().getContentType();
		String maxSize = getRequest().getSession().getServletContext().getInitParameter("maxSize");
		//String fileTypeRestriction = getRequest().getSession().getServletContext().getInitParameter("fileTypeRestriction");
		//String flag = "";
		if(contentType==null || !contentType.startsWith("multipart/form-data"))  //没有文件提交
		{
		}else{
			List files = getUpload();
			StringBuilder sb = new StringBuilder();
			for (int i = 0 ; i < files.size() ; i++) 
			{ 
				String fileName = (String) getUploadFileName().get(i);
				String fileType = fileName.substring((fileName.lastIndexOf("."))+1, fileName.length());
				//if(fileTypeRestriction.contains(fileName)){
					File ff = new File(files.get(i).toString());
					if(ff.length()>0 && ff.length() <= Integer.parseInt(maxSize))  //大于30M 30M= 30*1024*1024  
					{
						String url = String.valueOf(getRequest().getSession().getAttribute("SYS_FILEPATH"));
						String userId = getRequest().getParameter("userId");
						sysCerify.setCerifyUser(Long.parseLong(userId));
						sysCerify.setCerifyType(fileType);
						sysCerify.setCrttime(new Timestamp(System.currentTimeMillis()));
						Map fileMap = new HashMap();
						File file = new File(url);
						if ( ! (file.exists())  &&   ! (file.isDirectory()))  {
			                 boolean  creadok  =  file.mkdirs();
			                 if (creadok)  {
			                    System.out.println( " ok:创建文件夹成功！ " );
			                } else  {
			                    System.out.println( " err:创建文件夹失败！ " );                    
			                } 
			            } 
						String address = url + "/" + getUploadFileName().get(i);
						sysCerify.setCerifyPath(address);
						FileOutputStream fos = new FileOutputStream(address); 
						FileInputStream fis = new FileInputStream(files.get(i).toString()); 
						byte[] buffer = new byte[1024]; 
						int len = 0; 
						while ((len = fis.read(buffer)) > 0) 
						{ 
							fos.write(buffer, 0, len);
						} 
						fos.close();
						fis.close();
						sb.append(getUploadFileName().get(i));
						// System.out.println( " address --->"+address);     
						//保存数据----sysCerify对象
						getRequest().setAttribute("userid", userId);
						cerifyService.saveCerify(sysCerify);
						getRequest().setAttribute("message", "保存成功！");
						Long type = 0l;
						getRequest().setAttribute("type", type);
						//out.print("{\"result\":\"success\"}");
						logService.saveLogInfo(this.getLogBase(), "系统管理", "个人信息管理", "个人信息证书添加成功");
						//flag= "SUCCESS";
					}else if(ff.length() == 0){
						String cerifyDate = this.getRequest().getParameter("cerifyDate");
						String cerifyNo = this.getRequest().getParameter("cerifyNo");
						String cerifyName = this.getRequest().getParameter("cerifyName");
						String cerifyDesc = this.getRequest().getParameter("cerifyDesc");
						String cerifyOverdate = this.getRequest().getParameter("cerifyOverdate");
						String userId = this.getRequest().getParameter("userId");
						
						String [] cerifyDate1 = cerifyDate.split("-");
						String cerifyPastTime = Long.parseLong(cerifyDate1[0])+Long.parseLong(cerifyOverdate)+"-"+cerifyDate1[1]+"-"+cerifyDate1[2];
						
						addMessage("文件大小为空，不能上传！");
						Long type = 1l;
						getRequest().setAttribute("type", type);
						getRequest().setAttribute("cerifyDate", cerifyDate);
						getRequest().setAttribute("cerifyOverdate", cerifyOverdate);
						getRequest().setAttribute("cerifyPastTime", cerifyPastTime);
						getRequest().setAttribute("userId", userId);
						getRequest().setAttribute("cerifyNo", StringUtil.encodingUrl(cerifyNo));
						getRequest().setAttribute("cerifyName", StringUtil.encodingUrl(cerifyName));
						getRequest().setAttribute("cerifyDesc", StringUtil.encodingUrl(cerifyDesc));
						//logService.saveLogInfo(this.getLogBase(), "系统管理", "个人信息管理", "个人信息证书文件大小为空");
						return "uploadKong";
					}else{
						addMessage("文件大小超过限制！");
						Long type = 1l;
						getRequest().setAttribute("type", type);
						logService.saveLogInfo(this.getLogBase(), "系统管理", "个人信息管理", "个人信息证书文件大小超过限制");
						return "uploadXianZhi";
						//flag = "uploadError";
					}
				//}else{
				//	addMessage("该文件类型不允许上传，请上传doc、docx、xlsx、xls、gif、jpg、jpeg、png、bmp、zip、rar等类型的文件，当前文件类型为"+fileName);
				//	flag = "uploadError";
				//}
			}
		}
//		logService.saveLogInfo(this.getLogBase(), "文件保存功能成功", "附件管理", "");
		return "uploadSuccess";
	}
	 
	 public String checkOneCerifyById(){
		 try {
				Long id = Long.parseLong(getRequest().getParameter("id"));
			 	Long userId = Long.parseLong(getRequest().getParameter("userId"));
			 	getRequest().setAttribute("userId", userId);
			    sysCerify=cerifyService.checkOneCerifyById(id);
//			    getRequest().setAttribute("cerifyPastTime",  sysCerify.getCerifyPastTime().toString().substring(0, 10));
				return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	 }
	/**
	 * 修改用户里证书的信息
	 * @return
	 * @throws IOException
	 * @throws ServiceException
	 */
	public String updateCerify2Exec() throws Exception {
		setContentType();
		String contentType = this.getRequest().getContentType();
		String maxSize = getRequest().getSession().getServletContext().getInitParameter("maxSize");
		//String fileTypeRestriction = getRequest().getSession().getServletContext().getInitParameter("fileTypeRestriction");
		//String flag = "";
		if(contentType==null || contentType.startsWith("multipart/form-data"))  //没有文件提交
		{
		}else{
			List files = getUpload();
			StringBuilder sb = new StringBuilder();
			for (int i = 0 ; i < files.size() ; i++) 
			{ 
				String fileName = (String) getUploadFileName().get(i);
				fileName = fileName.substring((fileName.lastIndexOf("."))+1, fileName.length());
				//if(fileTypeRestriction.contains(fileName)){
					File ff = new File(files.get(i).toString());
					if(ff.length()>0 && ff.length() <= Integer.parseInt(maxSize))  //大于30M 30M= 30*1024*1024  
					{
						String url = String.valueOf(getRequest().getSession().getAttribute("SYS_FILEPATH"));
						String id = this.getRequest().getParameter("id");
						sysCerify.setId(Long.parseLong(id));
						sysCerify.setCerifyType(fileName);
						sysCerify.setMdfytime(new Timestamp(System.currentTimeMillis()));
						sysCerify.setCerifyPath(url);
						Map fileMap = new HashMap();
						File file = new File(url);
						if ( ! (file.exists())  &&   ! (file.isDirectory()))  {
			                 boolean  creadok  =  file.mkdirs();
			                 if (creadok)  {
			                    System.out.println( " ok:创建文件夹成功！ " );
			                } else  {
			                    System.out.println( " err:创建文件夹失败！ " );                    
			                } 
			            } 
						String address = url + "/" + getUploadFileName().get(i);
						FileOutputStream fos = new FileOutputStream(address); 
						FileInputStream fis = new FileInputStream(files.get(i).toString()); 
						byte[] buffer = new byte[1024]; 
						int len = 0; 
						while ((len = fis.read(buffer)) > 0) 
						{ 
							fos.write(buffer, 0, len);
						} 
						fos.close();
						fis.close();
						sb.append(getUploadFileName().get(i));
						// System.out.println( " address --->"+address);     
						//保存数据----sysCerify对象
						cerifyService.updateCerify(sysCerify);
						addMessage("修改成功！");
						//flag= "SUCCESS";
						
					}else if(ff.length() == 0){
						String cerifyDate = this.getRequest().getParameter("cerifyDate");
						String cerifyNo = this.getRequest().getParameter("cerifyNo");
						String cerifyName = this.getRequest().getParameter("cerifyName");
						String cerifyDesc = this.getRequest().getParameter("cerifyDesc");
						String cerifyOverdate = this.getRequest().getParameter("cerifyOverdate");
						String userId = this.getRequest().getParameter("userId");
						String id = this.getRequest().getParameter("id");
						sysCerify=cerifyService.checkOneCerifyById(Long.parseLong(id));
						addMessage("文件大小为空，不能上传！");
						getRequest().setAttribute("sysCerify", sysCerify);
						getRequest().setAttribute("userId", userId);
						getRequest().setAttribute("cerifyDate", cerifyDate);
						getRequest().setAttribute("cerifyOverdate", cerifyOverdate);
						getRequest().setAttribute("cerifyNo",  StringUtil.encodingUrl(cerifyNo));
						getRequest().setAttribute("cerifyName",  StringUtil.encodingUrl(cerifyName));
						getRequest().setAttribute("cerifyDesc",  StringUtil.encodingUrl(cerifyDesc));
						Long type = 1l;
						getRequest().setAttribute("type", type);
						return "uploadKong";
					}else{
						addMessage("文件大小超过限制！");
						Long type = 1l;
						getRequest().setAttribute("type", type);
						return "uploadXianZhi";
						//flag = "uploadError";
					}
				//}else{
				//	addMessage("该文件类型不允许上传，请上传doc、docx、xlsx、xls、gif、jpg、jpeg、png、bmp、zip、rar等类型的文件，当前文件类型为"+fileName);
				//	flag = "uploadError";
				//}
			}
		}
		String userId = getRequest().getParameter("userId");
		String id = getRequest().getParameter("id");
		sysCerify.setCerifyUser(Long.parseLong(userId));
		sysCerify.setId(Long.parseLong(id));
		//sysCerify.setCerifyPath(sysCerifys.getCerifyPath());
		sysCerify.setMdfytime(new Timestamp(System.currentTimeMillis()));
		cerifyService.updateCerify(sysCerify);
		getRequest().setAttribute("message", "修改成功！");
		Long type = 0l;
		getRequest().setAttribute("type", type);
		logService.saveLogInfo(this.getLogBase(), "系统管理", "个人信息管理", "个人信息证书修改成功");
//		logService.saveLogInfo(this.getLogBase(), "文件保存功能成功", "附件管理", "");
		return "uploadSuccess";
	}
	public String updateCerify1Exec() throws Exception {
		setContentType();
		String contentType = this.getRequest().getContentType();
		String maxSize = getRequest().getSession().getServletContext().getInitParameter("maxSize");
		//String fileTypeRestriction = getRequest().getSession().getServletContext().getInitParameter("fileTypeRestriction");
		//String flag = "";
		if(contentType==null || !contentType.startsWith("multipart/form-data"))  //没有文件提交
		{
		}else{
			List files = getUpload();
			StringBuilder sb = new StringBuilder();
			for (int i = 0 ; i < files.size() ; i++) 
			{ 
				String fileName = (String) getUploadFileName().get(i);
				String fileType = fileName.substring((fileName.lastIndexOf("."))+1, fileName.length());
				//if(fileTypeRestriction.contains(fileName)){
				File ff = new File(files.get(i).toString());
				if(ff.length()>0 && ff.length() <= Integer.parseInt(maxSize))  //大于30M 30M= 30*1024*1024  
				{
					String url = String.valueOf(getRequest().getSession().getAttribute("SYS_FILEPATH"));
					String id = this.getRequest().getParameter("id");
					String userId = getRequest().getParameter("userId");
					sysCerify.setCerifyUser(Long.parseLong(userId));
					sysCerify.setId(Long.parseLong(id));
					sysCerify.setCerifyType(fileType);
					sysCerify.setMdfytime(new Timestamp(System.currentTimeMillis()));
					Map fileMap = new HashMap();
					File file = new File(url);
					if ( ! (file.exists())  &&   ! (file.isDirectory()))  {
						boolean  creadok  =  file.mkdirs();
						if (creadok)  {
							System.out.println( " ok:创建文件夹成功！ " );
						} else  {
							System.out.println( " err:创建文件夹失败！ " );                    
						} 
					} 
					String address = url + "/" + getUploadFileName().get(i);
					sysCerify.setCerifyPath(address);
					FileOutputStream fos = new FileOutputStream(address); 
					FileInputStream fis = new FileInputStream(files.get(i).toString()); 
					byte[] buffer = new byte[1024]; 
					int len = 0; 
					while ((len = fis.read(buffer)) > 0) 
					{ 
						fos.write(buffer, 0, len);
					} 
					fos.close();
					fis.close();
					sb.append(getUploadFileName().get(i));
					// System.out.println( " address --->"+address);     
					//保存数据----sysCerify对象
					cerifyService.updateCerify(sysCerify);
					
					//flag= "SUCCESS";
				}else if(ff.length() == 0){
					String cerifyDate = this.getRequest().getParameter("cerifyDate");
					String cerifyNo = this.getRequest().getParameter("cerifyNo");
					String cerifyName = this.getRequest().getParameter("cerifyName");
					String cerifyDesc = this.getRequest().getParameter("cerifyDesc");
					String cerifyOverdate = this.getRequest().getParameter("cerifyOverdate");
					String userId = this.getRequest().getParameter("userId");
					String id = this.getRequest().getParameter("id");
					sysCerify=cerifyService.checkOneCerifyById(Long.parseLong(id));
					addMessage("文件大小为空，不能上传！");
					getRequest().setAttribute("sysCerify", sysCerify);
					getRequest().setAttribute("userId", userId);
					getRequest().setAttribute("cerifyDate", cerifyDate);
					getRequest().setAttribute("cerifyPastTime", (sysCerify.getCerifyPastTime().toString()).substring(0, 10));
					getRequest().setAttribute("cerifyOverdate", cerifyOverdate);
					getRequest().setAttribute("cerifyNo", StringUtil.encodingUrl( cerifyNo));
					getRequest().setAttribute("cerifyName",StringUtil.encodingUrl(cerifyName));
					getRequest().setAttribute("cerifyDesc",StringUtil.encodingUrl(cerifyDesc));
					Long type = 1l;
					getRequest().setAttribute("type", type);
					return "uploadKong";
				}else{
					addMessage("文件大小超过限制！");
					Long type = 1l;
					getRequest().setAttribute("type", type);
					return "uploadXianZhi";
					//flag = "uploadError";
				}
				//}else{
				//	addMessage("该文件类型不允许上传，请上传doc、docx、xlsx、xls、gif、jpg、jpeg、png、bmp、zip、rar等类型的文件，当前文件类型为"+fileName);
				//	flag = "uploadError";
				//}
			}
		}
		sysCerify.setMdfytime(new Timestamp(System.currentTimeMillis()));
		cerifyService.updateCerify(sysCerify);
		addMessage("修改成功！");
		Long type = 0l;
		getRequest().setAttribute("type", type);
		logService.saveLogInfo(this.getLogBase(), "系统管理", "个人信息管理", "个人信息证书修改成功");
		return "uploadSuccess";
	}
	
	/**
	 * 查询所有证书
	 * @throws Exception
	 */
	public void cerifyInfoExec() throws Exception{
		try {
			Map<String, String> filterMap = getPagerMap();
			String[] viewArray = { "ID","CERIFY_NO","CERIFY_NAME", "USERNAME",
					"CERIFY_DATE","CERIFY_TYPE", "CERIFY_OVERDATE","CERIFY_DESC","CERIFY_PAST_TIME"};
			String userid = getRequest().getParameter("userid");
			// 查询所有的数据
			PageResult result = cerifyService.querycerifyInfo(filterMap,userid);

			String returnStr = getColumnJson(result, viewArray);

			setContentType();
			PrintWriter out = getResponse().getWriter();
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 删除证书
	 * @throws IOException
	 * @throws ServiceException void
	 * @author 
	 * @date
	 */
	public void deleteCerityExec() throws IOException, ServiceException {
		PrintWriter out = getResponse().getWriter();
		try {
			String ids = getRequest().getParameter("ids");
			if (ids != null && !ids.isEmpty()) {
				cerifyService.deleteCerity(ids);
			}
			out.print("{\"ajaxResult\":\"success\"}");
			logService.saveLogInfo(this.getLogBase(), "系统管理", "个人信息管理", "个人信息删除证书成功");
		} catch (Exception e) {
			e.printStackTrace();
			out.print("{\"ajaxResult\":\"error\"}");
			logService.saveLogInfo(this.getLogBase(), "系统管理", "个人信息管理", "个人信息删除证书失败");
		}

	}
	/**
	 * 文件下载
	 * @return
	 * @throws IOException
	 * @throws ServiceException String
	 * @author 张海娜
	 * @throws UnsupportedEncodingException 
	 * @date 2012-9-27 上午10:30:13
	 */
	public void downloadExec() throws UnsupportedEncodingException
	{
		String id = getRequest().getParameter("id");
		sysCerify = cerifyService.findSysCerifyById(Long.parseLong(id));
		File downloadFile = new File(sysCerify.getCerifyPath());
		if(downloadFile.exists())
		{
			getResponse().setHeader("Server","www.sinosoft.com");
			getResponse().setHeader("Content-Type", "application/octet-stream");
			getResponse().setHeader("Content-Length", String.valueOf(downloadFile.length()));

			getResponse().setHeader("Content-Disposition", "attachment; filename=\"" + java.net.URLEncoder.encode(sysCerify.getCerifyPath(),"UTF-8").replace( "+",   "%20")  + "\"");	
			try {
				OutputStream downloadStream=getResponse().getOutputStream();
				FileInputStream fin=new FileInputStream(downloadFile);
				byte[] b=new byte[1024];				
				int length=fin.read(b);
				while(length>0)
				{
					downloadStream.write(b,0,length);
					length=fin.read(b);
				}
				downloadStream.flush();
				fin.close();	
				addMessage("下载成功！");
			} catch (IOException e) {
				e.printStackTrace();
			}			
		}
		else
		{
			addMessage("下载失败！");
			getResponse().setHeader("Content-Type", "text/html; charset=UTF-8");
			try {
				addMessage("下载失败！");
				getResponse().getWriter().write("<html>");
				getResponse().getWriter().write("<head>");
				getResponse().getWriter().write("</head>");
				getResponse().getWriter().write("<body>");
				getResponse().getWriter().write("文件没有找到<br>");
				getResponse().getWriter().write("<a href='#' onclick='javascript:history.back(-1)'>返回</a>");
				getResponse().getWriter().write("</body>");
				getResponse().getWriter().write("</html>");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		addMessage("下载成功！");
	}
	
	public CerifyService getCerifyService() {
		return cerifyService;
	}
	public void setCerifyService(CerifyService cerifyService) {
		this.cerifyService = cerifyService;
	}
	public SysCerify getSysCerify() {
		return sysCerify;
	}
	public void setSysCerify(SysCerify sysCerify) {
		this.sysCerify = sysCerify;
	}
	
	public List getUpload() {
		return upload;
	}
	public void setUpload(List upload) {
		this.upload = upload;
	}
	public List getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(List uploadContentType) {
		this.uploadContentType = uploadContentType;
	}
	public List getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(List uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public LogService getLogService() {
		return logService;
	}

	public void setLogService(LogService logService) {
		this.logService = logService;
	}
	
	
}
